package com.syg;

import com.syg.cycle.Cycle_A;
import com.syg.cycle.Cycle_B;

import java.lang.reflect.Field;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author ps
 */
public class TestCycle {

    /**
     * 声明容器
     */
    private final static Map<String, Object> SINGLETON_OBJECTS = new ConcurrentHashMap<>(256);

    public static void main(String[] args) throws InstantiationException, IllegalAccessException {
        System.out.println(getBean(Cycle_A.class).getCycleB());
        System.out.println(getBean(Cycle_B.class).getCycleA());

    }

    private static <T> T getBean(Class<T> beanClass) throws IllegalAccessException, InstantiationException {
        String beanName = beanClass.getSimpleName().toLowerCase();
        if (SINGLETON_OBJECTS.containsKey(beanName)) {
            return (T) SINGLETON_OBJECTS.get(beanName);
        }

        // 实例化对象入缓存
        Object obj = beanClass.newInstance();
        SINGLETON_OBJECTS.put(beanName, obj);
        // 属性填充,补全对象(与beanClass.getDeclaredFields()的区别)
        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            Class<?> fieldClass = field.getType();
            String fieldBeanName = fieldClass.getSimpleName().toLowerCase();
            field.set(obj, SINGLETON_OBJECTS.containsKey(fieldBeanName) ? SINGLETON_OBJECTS.get(fieldBeanName) : getBean(fieldClass));
            field.setAccessible(false);
        }
        return (T) obj;
    }
}
